/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package convenios.bd;

import associados.classes.Associado;
import conexao.ConexaoSingleton;
import conexao.DAOException;
import convenios.classes.Convenio;
import java.util.Collection;
import java.util.List;
import javax.management.Query;
import javax.persistence.EntityManager;

public class ConvenioDAO implements IConvenioDAO {

    private EntityManager manager;

    public ConvenioDAO() throws DAOException {
        try {
            manager = ConexaoSingleton.getConexao();
        } catch (Exception ex) {
            throw new DAOException("Sem conexão com a Base de Dados", ex);
        }
    }

    public Convenio getConvenio(Integer codigo) throws DAOException {
        try {
            Convenio c = manager.find(Convenio.class, codigo);
            return c;

        } catch (Exception e) {
            throw new DAOException("Sem conexão com o banco de dados", e);
        }
    }

    public void salvar(Convenio c) throws DAOException {

        try {
            //abrindo uma transação
            manager.getTransaction().begin();
            manager.persist(c);
            //fechando uma transação
            manager.getTransaction().commit();


        } catch (Exception ex) {
            if (manager.getTransaction().isActive()) {
                //em caso de erro o rollback desfaz o que ficou pela metade
                manager.getTransaction().rollback();
            }
            throw new DAOException("Sem conexao com a base", ex);
        }
    }

    public List<Convenio> getConvenios() throws DAOException {
        try {

            javax.persistence.Query q = manager.createQuery("Select c from Convenio c");
            return q.getResultList();

        } catch (Exception ex) {
            throw new DAOException("Erro na consulta a base de dados de Convenio", ex);
        }
    }

    public void excluirConvenio(Convenio convenio) throws DAOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void setConvenio(Convenio convenio) throws DAOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public List<Associado> getNomeAssocaiado(String nome) throws DAOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public Convenio getCNPJ(String cnpj) throws DAOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public Convenio getNome(String nome) throws DAOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void desconecta() {
        try {
            manager.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

